package com.example.toolproject.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.toolproject.demo.domain.*;
import com.example.toolproject.demo.service.*;
import com.example.toolproject.demo.util.ResultBean;
import com.example.toolproject.demo.util.excel.ExcelUtils;
import com.example.toolproject.demo.util.jwt.JwtUtil;
import com.example.toolproject.demo.util.redis.RedisUtil;
import com.kennycason.kumo.WordFrequency;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName EchartController
 * @Description TODO          图表请求，几乎该项目所有图表都在
 * @Author lvyongwei
 * @Date 2020-07-07 10:13
 **/
@Controller
@CrossOrigin
@RequestMapping("/echarts")
public class EchartController {

    private Logger logger= LoggerFactory.getLogger(EchartController.class);

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private LabReportService labReportService;

    @Autowired
    private DataSearchService dataSearchService;

    @Autowired
    private ScenicSportService scenicSportService;

    @Autowired
    private PlanningReportService planningReportService;

    @Autowired
    private ExcelUtils excelUtils;

    /**
     * 获取主页显示的数据以及，图表信息
     * @return
     */
    @GetMapping("/getCount")
    @ResponseBody
    public ResultBean getEchart(){
        /**
         * 创建页面显示的图表对象
         */
        LoginPageMessage loginPageMessage=new LoginPageMessage();
        /**
         * 获取成绩分布
         */
        LoginPageMessage score=labReportService.getScoreUser();
        /**
         * 将对象的值赋值给另一个对象
         */
        BeanUtils.copyProperties(score,loginPageMessage);
        loginPageMessage.setExperimentNumber(labReportService.getAllLabReportCount());
        /**
         * 获取用户角色分布
         */
        LoginPageMessage userCount=userService.getUserCount();
        /**
         * 设置角色人数值
         */
        loginPageMessage.setUserTotal(userCount.getUserTotal());
        loginPageMessage.setStudentNumber(userCount.getStudentNumber());
        loginPageMessage.setTeacherNumber(userCount.getTeacherNumber());
        loginPageMessage.setTouristsNumber(userCount.getTouristsNumber());
        /**
         * 訪問總人數
         */
        if(StringUtils.isEmpty(redisUtil.get("wlrh_accessNumber")) || redisUtil.get("wlrh_accessNumber")==null){
            loginPageMessage.setAccessNumber(1);
            redisUtil.set("wlrh_accessNumber",1);
        }else{
            long accessNumber=Long.valueOf(redisUtil.get("wlrh_accessNumber").toString());
            accessNumber++;
            //将访问次数放入redis
            redisUtil.set("wlrh_accessNumber",accessNumber);
            loginPageMessage.setAccessNumber(accessNumber);
        }

        if(StringUtils.isEmpty(loginPageMessage) || loginPageMessage==null){
            return ResultBean.error("未获取到数据");
        }
        return ResultBean.success(loginPageMessage);
    }


    @Autowired
    private com.example.toolproject.demo.util.ciyun.wordCloud wordCloud;

    /**
     * 分词
     * @param request
     * @param type
     * @return
     */
    @GetMapping("/getAllWord")
    @ResponseBody
    public ResultBean getAllWord(HttpServletRequest request, int type){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        /**
         * 根据类型获取到数据信息，以及用户引用获取数据
         */
        /**
         * 根据类型获取到数据信息
         * List<String> list=dataSearchService.getDataSearch(type);
         */
        System.out.println(u.getId());
        List<String> list=dataSearchService.getDataSearch2(u.getId(),type);
        if(list==null || list.size()==0){
            return ResultBean.error("没有获取到信息",list);
        }
        try{
            List<WordFrequency> frequencyList = wordCloud.getWordCloud(list);
            if(frequencyList.size()==0){
                return ResultBean.error("没有获取到数据",list);
            }
            return ResultBean.success("获取到数据",frequencyList);
        }catch (Exception e){
            return ResultBean.error("没有获取到数据",null);
        }
    }

    /**
     * 获取城市出现频率
     * @param request
     * @return
     */
    @GetMapping("/getCityCount")
    @ResponseBody
    public ResultBean getCityScenicSportCount(HttpServletRequest request){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        try{
            /**
             * 执行获取城市数量
             */
            List<Map<String,Object>> list=scenicSportService.getCityCount();
            return ResultBean.success("获取数据成功",list);
        }catch (Exception e){
            return ResultBean.error("获取数据失败");
        }
    }


    /**
     * 获取策划报告成绩分布
     * @param request
     * @return
     */
    @GetMapping("/getPlanningReportScore")
    @ResponseBody
    public ResultBean getPlanningReportScore(HttpServletRequest request){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        try {
            return ResultBean.success("获取数据成功",planningReportService.getPlanningReportScore());
        }catch (Exception e){
            return ResultBean.error("获取数据失败");
        }
    }



    /**
     * 分词
     * @param request
     * @param type
     * @return
     */
    @GetMapping("/exportWord")
    public void getAllWord2(HttpServletRequest request, HttpServletResponse response, int type, String token){
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        /**
         * 根据类型获取到数据信息，以及用户引用获取数据
         */
        List<String> list=dataSearchService.getDataSearch2(u.getId(),type);
        /**
         * 执行分词
         */
        List<WordFrequency> frequencyList = wordCloud.getWordCloud(list);
        /**
         * 创建导出字实体
         */
        List<Word> words=new ArrayList<Word>();
        /**
         * 遍历
         */
        for(WordFrequency word:frequencyList){
            Word word1=new Word();
            word1.setWord(word.getWord());
            word1.setCount(word.getFrequency());
            words.add(word1);
        }
        /**
         * 导出操作
         */
        excelUtils.cooperationData(request,response,words,"词语出现频率", Word.class);
    }


    /**
     * 获取省份对应的人数
     * @param request
     * @return
     */
    @GetMapping("/provinceCount")
    @ResponseBody
    public ResultBean provinceCount(HttpServletRequest request){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        try{
            /**
             * 获取所有的省份
             */
            List<String> province=userService.getAllProvince();
            /**
             * 获取教师对应所有省份人数
             */
            List<Object> teacherProvince=userService.getTeacherProvince();
            /**
             * 获取学生对应所有省份人数
             */
            List<Object> studentProvince=userService.getStudentProvince();
            /**
             * 获取游客对应所有省份人数
             */
            List<Object> touristProvince=userService.getTouristProvince();
            /**
             * 配合前端echart视图封装对象
             */
            List<UserProvinceCount> list=new ArrayList<>();
            list.add(new UserProvinceCount("省份",province));
            list.add(new UserProvinceCount("高校教师",teacherProvince));
            list.add(new UserProvinceCount("高校学生",studentProvince));
            list.add(new UserProvinceCount("游客",touristProvince));
            return ResultBean.success("获取省份对应人数成功",list);
        }catch(Exception e){
            return ResultBean.error("获取省份对应人数失败");
        }
    }


    /**
     * 获取城市出现频率   (数据爬取)
     * @param request
     * @return
     */
    @GetMapping("/getTouristCount")
    @ResponseBody
    public ResultBean getTouristCount(HttpServletRequest request){
        //获取前端传来的token
        String token = request.getHeader("Authorization");
        if(token==null || token.equals("")){
            return ResultBean.error("无token,请先登录");
        }
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt,User.class);
        //判断token是否失效
        if(u == null){
            return ResultBean.error("token无效");
        }
        try{
            /**
             * 执行获取城市数量
             */
            List<Map<String,Object>> list=scenicSportService.getTouristCount();
            ResultBean resultBean=ResultBean.success("获取数据成功",list);
            resultBean.put("date",scenicSportService.getNewDate());
            return resultBean;
        }catch (Exception e){
            return ResultBean.error("获取数据失败");
        }
    }

}
